package g

type ListNode struct {
	Val  int
	Next *ListNode
}

/*
 * @lc app=leetcode.cn id=21 lang=golang
 *
 * [21] 合并两个有序链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
	return mergeTwoListsCommon(list1, list2)
}

func mergeTwoListsCommon(l1 *ListNode, l2 *ListNode) *ListNode {
	ret := ListNode{}
	p := &ret
	for l1 != nil && l2 != nil {
		if l1.Val < l2.Val {
			p.Next = l1
			l1 = l1.Next
		} else {
			p.Next = l2
			l2 = l2.Next
		}
		p = p.Next
	}
	if l1 != nil {
		p.Next = l1
	} else {
		p.Next = l2
	}
	return ret.Next
}

func mergeTwoListsRecursion(l1 *ListNode, l2 *ListNode) *ListNode {
	if l2 == nil {
		return l1
	} else if l1 == nil {
		return l2
	} else if l1.Val < l2.Val {
		l1.Next = mergeTwoListsRecursion(l1.Next, l2)
		return l1
	} else {
		l2.Next = mergeTwoListsRecursion(l2.Next, l1)
		return l2
	}
}

// @lc code=end
